package com.at.bilibili.service.handler;

import com.at.bilibili.domain.JsonResponse;
import com.at.bilibili.domain.exception.ConditionException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE) // 给予最高优先级
public class CommonGlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class) // 用来表示异常处理器 处理所有异常
    @ResponseBody
    public JsonResponse<String> commonExceptionHandler(HttpServletRequest request, Exception e){

        String errorMsg = e.getMessage();

        if(e instanceof ConditionException){
            String errorCode = ((ConditionException) e).getCode();
            return new JsonResponse<>(errorCode, errorMsg);
        }
        else {
            return new JsonResponse<>("500",errorMsg);
        }

    }


}
